﻿using System;
using System.Collections.Generic;
using System.Xml;
using PSE.Updater.Common;
using PSE.Framework.ErrorLogging;

namespace PSE.Updater.Client.Engine
{
    public class InstalledSystems
    {
        private const string CONST_SYSTEM = "{0}Parameters_v";
        private const string CONST_FOLDER = "BMFBOVESPA";

        public IList<SystemInformation> List()
        {
            List<SystemInformation> items = new List<SystemInformation>();

            try
            {
                string path = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                string[] directories = System.IO.Directory.GetDirectories(System.IO.Path.Combine(path, CONST_FOLDER));
                foreach (string directory in directories)
                {
                    string[] files = System.IO.Directory.GetFiles(directory);
                    string[] folders = directory.Split('\\');
                    string systemRoot = folders[folders.Length - 1];
                    string system = string.Format(CONST_SYSTEM, systemRoot);
                    foreach (var file in files)
                    {
                        string xmlFile = System.IO.Path.GetFileName(file);
                        if (xmlFile.StartsWith(system))
                        {
                            string version = xmlFile.Replace(system, string.Empty).Replace(".xml", string.Empty);
                            int majorVersion = int.Parse(version);

                            string installationPath = PSE.Updater.Common.Util.Instance.GetInstallationPath(systemRoot);

                            SystemInformation systemDetail = new SystemInformation(systemRoot, majorVersion, installationPath);
                            items.Add(systemDetail);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.WriteLog(LogType.Warning, ex);
            }

            return items;
        }

        private string GetInstallationPath(string file, string systemName)
        {
            try
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(file);
                string path = xml.ChildNodes.Item(1).Attributes["InstallationPath"].Value;
                
                return System.IO.Path.Combine(path, systemName);
            }
            catch (Exception ex)
            {
                ErrorLogger.WriteLog(LogType.Error, ex);
                //throw ex;
                return string.Empty;
            }
        }
    }
}